package handlers

import (
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/vmihailenco/msgpack/v5"
	"gogogo-server/gameserver/game"
	"gogogo-server/gameserver/protocols"
	"gogogo-server/gameserver/service"
	"gogogo-server/share/utils"
	"log"
)

type SingleRoom struct {
	Uid    uint64
	Master uint64 // 房主id
}

type RoomHandler struct {
	// 可以添加所需的属性和依赖项
	AllRooms map[uint64]*SingleRoom
}

func NewRoomHandler() *RoomHandler {
	return &RoomHandler{
		// 初始化
	}
}

func (h *RoomHandler) HandleMessage(conn *websocket.Conn, msg *protocols.Message) error {
	switch msg.Event {
	case "room.create":
		return h.handleCreateRoom(conn, msg.Data)
	case "room.join":
		return h.handleJoinRoom(conn, msg.Data)
	// 更多消息类型...
	default:
		return fmt.Errorf("unsupported message type: %s", msg.Event)
	}
}

func (h *RoomHandler) handleCreateRoom(conn *websocket.Conn, data []byte) error {
	// 处理创建房间的逻辑
	// 在实际应用中，您可以生成唯一的房间ID，创建房间对象，然后将房间添加到适当的数据结构中
	roomID := utils.IDGenerator.GenerateRoomID()
	room := game.NewRoom(roomID)
	// 将房间添加到房间列表
	game.AddRoom(room)

	// 创建玩家并加入房间
	player := playerConns[conn]
	err := room.AddPlayer(player)
	if err != nil {
		return fmt.Errorf("invalid data type for JoinRoom")
	}
	data, err = msgpack.Marshal(protocols.CreateRoomResponse{ID: roomID})
	if err != nil {
		log.Println("MessagePack Marshal Error:", err)
		return err
	}
	successMsg := protocols.Message{
		Event: "room.create",
		Data:  data,
	}
	err = service.SendMsg(conn, successMsg)
	if err != nil {
		return err
	}
	return nil
}

func (h *RoomHandler) handleJoinRoom(conn *websocket.Conn, data []byte) error {
	// 处理加入房间的逻辑
	var loginData protocols.JoinRoomRequest
	err := msgpack.Unmarshal(data, &loginData)
	// 处理创建房间的逻辑
	if err != nil {
		return fmt.Errorf("failed to unmarshal login data: %v", err)
	}

	room, exists := game.GetRoom(loginData.ID)
	if !exists {
		// 如果房间不存在，向客户端发送错误消息
		errMsg := protocols.Message{
			Event: "error",
			//Data: "Room not found",
		}
		service.SendMsg(conn, errMsg)
		log.Printf("Room not found: ID=%s\n", loginData.ID)
		return nil
	}
	// 创建玩家并加入房间
	player := playerConns[conn]
	err = room.AddPlayer(player)
	if err != nil {
		return fmt.Errorf("invalid data type for JoinRoom")
	}

	// 在实际应用中，您可以将玩家添加到房间，执行加入房间的逻辑
	// 这里仅向客户端发送成功加入房间的消息
	data, err = msgpack.Marshal(protocols.JoinRoomResponse{ID: loginData.ID})
	if err != nil {
		log.Println("MessagePack Marshal Error:", err)
		return err
	}
	successMsg := protocols.Message{
		Event: "room.join",
		//Data: protocols.JoinRoomResponse{
		//	ID: roomData.ID},
	}
	service.SendMsg(conn, successMsg)
	log.Printf("Player joined room: ID=%s\n", loginData.ID)
	return nil
}
